/*
     Copyright 2007 Joseph M. Ferner

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using log4net;
using log4net.Config;
using NMock2;
using NUnit.Framework;
using OpenServers.Net.Common;
using OpenServers.Net.Common.FileSystem;
using OpenServers.Net.Common.Listener;
using OpenServers.Net.Common.Security;
using OpenServers.Net.Common.User;

namespace OpenServers.Net.FtpServer {
    [TestFixture]
    public class IntegrationTest : BaseNMockTest {
        private static readonly ILog log = LogManager.GetLogger(typeof(IntegrationTest));
        private const string A_TXT_CONTENTS = "Test date for a.txt";

        private FtpServer _ftpServer;
        private string _workingDirectory;
        private ISecurityProvider _securityProvider;
        private IFileSystem _fileSystem;
        private IUser _user;
        private IFile _file1;
        private IDirectory _dir1;
        private IDirectory _rootDir;
        private IList<IFileSystemObject> _fileList;

        [SetUp]
        public override void SetUp() {
            base.SetUp();
            BasicConfigurator.Configure();

            _securityProvider = Mocks.NewMock<ISecurityProvider>();

            _fileSystem = Mocks.NewMock<IFileSystem>();

            _rootDir = Mocks.NewMock<IDirectory>();

            _file1 = Mocks.NewMock<IFile>();

            _dir1 = Mocks.NewMock<IDirectory>();

            _fileList = new List<IFileSystemObject>();

            _user = Mocks.NewMock<IUser>();

            _workingDirectory = Path.GetTempPath();

            _ftpServer = new FtpServer();
            _ftpServer.Listeners.Add(new NonsecureTcpListener(FtpServer.DEFAULT_NONSECURE_PORT));
            _ftpServer.SecurityProvider = _securityProvider;
            _ftpServer.FileSystem = _fileSystem;
            _ftpServer.Start();
        }

        [TearDown]
        public override void TearDown() {
            _ftpServer.Stop();

            base.TearDown();
        }

        [Test]
        public void IntegrationTestLoginDownloadFile() {
            log.Debug("IntegrationTestLogin");

            Stream fileStream = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(A_TXT_CONTENTS));

            Expect.Once.On(_securityProvider).Method("ValidateUser").With("user1", "pass1").Will(Return.Value(_user));
            Expect.Once.On(_fileSystem).Method("GetFile").With("/a.txt").Will(Return.Value(_file1));
            Expect.Once.On(_securityProvider).Method("CanRead").With(_user, _file1).Will(Return.Value(true));
            Expect.Once.On(_file1).GetProperty("Exists").Will(Return.Value(true));
            Expect.Once.On(_file1).Method("OpenInputStream").Will(Return.Value(fileStream));

            StringBuilder commands = new StringBuilder();
            commands.AppendLine("user1");
            commands.AppendLine("pass1");
            commands.AppendLine("get a.txt");
            ExecuteFtp("localhost", commands.ToString());
            Assert.IsTrue(File.Exists(Path.Combine(_workingDirectory, "a.txt")));
            string fileContents = File.ReadAllText(Path.Combine(_workingDirectory, "a.txt"));
            Assert.AreEqual(A_TXT_CONTENTS, fileContents);
        }

        [Test]
        public void IntegrationTestLoginUploadFile() {
            log.Debug("IntegrationTestLogin");

            MemoryStream fileStream = new MemoryStream();

            File.WriteAllText(Path.Combine(_workingDirectory, "a.txt"), A_TXT_CONTENTS);

            Expect.Once.On(_securityProvider).Method("ValidateUser").With("user1", "pass1").Will(Return.Value(_user));
            Expect.Once.On(_fileSystem).Method("GetFile").With("/a.txt").Will(Return.Value(_file1));
            Expect.Once.On(_file1).GetProperty("Parent").Will(Return.Value(_dir1));
            Expect.Once.On(_securityProvider).Method("CanWrite").With(_user, _dir1).Will(Return.Value(true));
            Expect.Once.On(_file1).Method("OpenOutputStream").Will(Return.Value(fileStream));

            StringBuilder commands = new StringBuilder();
            commands.AppendLine("user1");
            commands.AppendLine("pass1");
            commands.AppendLine("put a.txt");
            ExecuteFtp("localhost", commands.ToString());
            byte[] fileStreamData = fileStream.ToArray();
            Assert.AreEqual(A_TXT_CONTENTS.Length, fileStreamData.Length);
            string fileContents = ASCIIEncoding.ASCII.GetString(fileStreamData);
            Assert.AreEqual(A_TXT_CONTENTS, fileContents);
        }

        [Test]
        public void IntegrationTestListDirectory() {
            log.Debug("IntegrationTestLogin");

            Expect.Once.On(_securityProvider).Method("ValidateUser").With("user1", "pass1").Will(Return.Value(_user));
            Expect.Once.On(_fileSystem).Method("GetDirectory").With("/").Will(Return.Value(_rootDir));
            Expect.Once.On(_rootDir).GetProperty("Exists").Will(Return.Value(true));
            Expect.Once.On(_securityProvider).Method("CanRead").With(_user, _rootDir).Will(Return.Value(true));
            _fileList.Add(_file1);
            _fileList.Add(_dir1);
            Expect.AtLeastOnce.On(_rootDir).Method("GetItems").Will(Return.Value(_fileList));
            Expect.AtLeastOnce.On(_file1).GetProperty("Name").Will(Return.Value("a.txt"));
            Expect.AtLeastOnce.On(_dir1).GetProperty("Name").Will(Return.Value("dir1"));

            StringBuilder commands = new StringBuilder();
            commands.AppendLine("user1");
            commands.AppendLine("pass1");
            commands.AppendLine("ls");
            ExecuteFtp("localhost", commands.ToString());
        }

        private void ExecuteFtp(string hostName, string commands) {
            commands = string.Format("open {0}\n{1}\nbye\n", hostName, commands);

            string ftpExecutable = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "ftp.exe");
            string tempFileName = Path.GetTempFileName();
            File.WriteAllText(tempFileName, commands);
            Process process = new Process();
            process.StartInfo.FileName = ftpExecutable;
            process.StartInfo.WorkingDirectory = _workingDirectory;
            process.StartInfo.Arguments = String.Format("\"-s:{0}\"", tempFileName);
            process.StartInfo.UseShellExecute = false;
            //process.StartInfo.CreateNoWindow = true;
            //process.StartInfo.RedirectStandardInput = true;
            //process.StartInfo.RedirectStandardError = true;
            //process.StartInfo.RedirectStandardOutput = true;
            process.Start();
            process.WaitForExit(60000);
            string standardError = null;
            //standardError = process.StandardError.ReadToEnd();
            string standardOutput = null;
            //standardOutput = process.StandardOutput.ReadToEnd();

            log.Debug(standardOutput);
            log.Error(standardError);
        }
    }
}
